package cn.bdqn.smbms.controller;

import cn.bdqn.smbms.entity.User;
import cn.bdqn.smbms.service.UserService;
import cn.bdqn.smbms.util.UUIDUtil;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
public class IndexController {

    @Autowired
    private UserService userService;
    //显示登录
    @RequestMapping("/login")
    public String showLogin() {
        return "login";
    }

    //显示upload
    @RequestMapping("/upload")
    public String showUpload(){
        return "upload";
    }

    //上传文件
   @RequestMapping("/upload.do")
    public String doUpload(
            @RequestParam("userName")
            String userName,
            @RequestParam("pic")
            MultipartFile[] pic,
            HttpServletRequest request,
            Model model
   ){
        String path = request.getServletContext().getRealPath("statics"+File.separator+"upload");//路径
        List<String> picNames = new ArrayList<>();
        for(MultipartFile myPic:pic){
            if(!myPic.isEmpty()){
                String oldName = myPic.getOriginalFilename();//获取文件名
                System.out.println(oldName+"大小:"+myPic.getSize()+",name"+myPic.getName());
                File fileTo = new File(path,oldName);
                try {
                    myPic.transferTo(fileTo);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                picNames.add(oldName);
            }
        }
       model.addAttribute("userName",userName);
       model.addAttribute("picNames",picNames);
       return "showPic";
    }

    //注销
    @RequestMapping("/logout.html")
    public String logout(HttpSession session){
        session.invalidate();
        return "login";
    }

    //显示主页
    @RequestMapping("/main.html")
    public String showMain(){
        return "frame";
    }

    //处理登录
    @RequestMapping("/login.html")
    public String doLogin(
            @RequestParam
                    String userCode,
            @RequestParam
                    String userPassword,
            Model model,
            HttpSession session
    ){
        User user = userService.findByCodeAndPwd(userCode,userPassword);
        if(user!=null){
            session.setAttribute("userSession",user);
            return  "redirect:/main.html";
        }else{
            model.addAttribute("msg","用户名或密码不正确,登录失败");
            return "login";
        }
    }
}
